/**
 * 
 */
package com.wubo.sec.core;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wubo
 * @CreateDate 2010-8-1
 * @version 1.0.01
 */
public class HttpServletRequestHolder {
	
	private static ThreadLocal<HttpServletRequest> httpServletRequestHolder  = new ThreadLocal<HttpServletRequest>();

	static void set(HttpServletRequest request){
		httpServletRequestHolder.set(request);
	}
	
	static void remove(){
		httpServletRequestHolder.remove();
	}
	
	public static HttpServletRequest getHttpServletRequest(){
		return httpServletRequestHolder.get();
	}
	
	public static String getIP(){
		HttpServletRequest request = getHttpServletRequest();
		if(request != null){
			return getClientIP(request);
		}
		return "-";
	}
	
	private static String getClientIP(HttpServletRequest request){
		String ip = request.getHeader("x-real-ip");
		
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("x-forwarded-for");
			if(ip != null) {
				ip=ip.split(",")[0].trim();
			}
		}
		
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {             
			ip = request.getHeader("Proxy-Client-IP");
		}
		
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		
		
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		
		return ip;
	}
}
